import React, { Component, Fragment } from 'react';
import { connect } from 'react-redux';
import { Form, Input, Button, Icon } from 'antd';
import successImg from './style/image/success.png';
import api from '../../utils/api';
import './style/css/Wechat.less';

class Wechat extends Component {
  constructor(props) {
    super(props);
    this.state = {
      successAlert: false,
      error: false,
      errorTitle: ''
    };
  }

  // 截取浏览器地址中的code
  getRequest() {
    const url = window.location.href;
    const theRequest = {};
    if (url.indexOf('?') !== -1) {
      const index = url.indexOf('?');
      const str = url.substr(index + 1);
      const strs = str.split('&');
      for (let i = 0; i < strs.length; i += 1) {
        theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]);
      }
    }
    return theRequest;
  }

  onSubmit = () => {
    const { form } = this.props;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      this.onBind(values);
    });
  }

  onBind = (values) => {
    const request = this.getRequest();
    const { form } = this.props;
    api({
      method: 'POST',
      url: 'wx/bind',
      data: {
        code: request.code,
        mobile: values.mobile,
        password: values.password,
      }
    }).then((res) => {
      if (res.data.success) {
        this.setState({
          successAlert: true
        });
        form.resetFields();
      }
    }).catch((err) => {
      const { data } = err;
      this.setState({
        error: true,
        errorTitle: data.message || '绑定失败'
      });
      setTimeout(() => {
        this.setState({
          error: false,
          errorTitle: ''
        }, () => {
          window.location.href = '/wechat';
        });
      }, 2000);
    });
  }

  render() {
    const { successAlert, error, errorTitle } = this.state;
    const { form } = this.props;
    const { getFieldDecorator } = form;
    const FormItem = Form.Item;
    return (
      <Fragment>
        { successAlert ?
          <div className="Wechat-alert">
            <div className="alert-icon">
              <img src={successImg} alt="" />
            </div>
            <div className="alert-content">绑定成功</div>
          </div> :
          <div className="Wechat">
            <Form>
              <FormItem label="手机号：" {...this.formLayout}>
                {getFieldDecorator('mobile', {
                  rules: [{ required: true, message: '请输入手机号' }],
                })(
                  <Input placeholder="请输入手机号" />
                )}
              </FormItem>
              <FormItem label="密码：" {...this.formLayout} style={{ marginTop: '10px' }}>
                {getFieldDecorator('password', {
                  rules: [{ required: true, message: '请输入密码' }],
                })(
                  <Input type="password" placeholder="请输入密码" />
                )}
              </FormItem>
            </Form>
            <Button className="submit-button" onClick={this.onSubmit}>绑定</Button>
            <div className="wechat-alert-title">输入云平台的登录帐号后就可以和云平台绑定，<br />绑定成功后您就可以在微信公众号上收到平台的设备告警等通知。</div>
            { error ?
              <div className="wechat-alert-toast">
                <Icon type="close" className="toast-icon" />
                <p className="toast-p">{errorTitle || '绑定失败'}</p>
              </div> : null}
          </div>
        }
      </Fragment>

    );
  }
}
export default Form.create()(connect()(Wechat));
